const path = require("path");
const Koa = require("koa");
const app = new Koa();
const views = require("koa-views");
const json = require("koa-json");
const onerror = require("koa-onerror");
const bodyparser = require("koa-bodyparser");
const logger = require("koa-logger");
const session = require("koa-session");
const redisStore = require("koa-redis");
const koaNunjucks = require("koa-nunjucks-2");
const koaStatic = require("koa-static");

const { REDIS_CONF } = require("./conf/db");
const { isProd } = require("./utils/env");
const { SESSION_SECRET_KEY } = require("./conf/secretKeys");
// 路由
const errorViewRouter = require("./routes/view/error");
const userViewRouter = require("./routes/view/user");
const userAPIRouter = require("./routes/api/user");
const utilsAPIRouter = require("./routes/api/utils");
const index = require("./routes/index");


// error handler
let onerrorConf = {};
if (isProd) {
  onerrorConf = {
    redirect: "/error"
  };
}
onerror(app, onerrorConf);  // 在页面中显示错误信息

app.use(koaStatic(__dirname + "/public"));
app.use(koaStatic(path.join(__dirname, "..", "uploadfiles")));

// middlewares
app.use(bodyparser({
  enableTypes: ["json", "form", "text"]
}));
app.use(json());
app.use(logger());  // 日志

// app.use(views(__dirname + "/views", {
//   // map: { ".njk": "nunjucks" }
//   extension: "njk"
// }));
app.use(koaNunjucks({
  ext: "html",
  path: __dirname + "/views",
}));

debugger;
// session 配置 数据加密 ，密匙 最好复杂一些
app.keys = [SESSION_SECRET_KEY];
app.use(session({
  key: "weibo.sid", // cookie name 默认是 koa.sid 用户的一个标识
  prefix: "weibo:sess:", // redis key 前缀 默认是"koa:sess""
  cookie: {
    path: "/",
    httpOnly: true, // 只能服务端更改cookie，客户端不可以更改cookie
    maxAge: 24 * 60 * 60 * 1000 // 过期时间 ms
  },
  // ttl: 24 * 60 * 60 * 1000 可以设置redis过期时间 ，可以不写会与cookie过期时间一致
  store: redisStore({
    // all: "127.0.0.1:6379"
    all: `${REDIS_CONF.host}:${REDIS_CONF.port}`
  })
}, app));
// logger 日志
// app.use(async (ctx, next) => {
//   const start = new Date()
//   await next()
//   const ms = new Date() - start
//   console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
// })

// routes
app.use(index.routes(), index.allowedMethods());
app.use(userViewRouter.routes(), userViewRouter.allowedMethods());
app.use(userAPIRouter.routes(), userAPIRouter.allowedMethods());
app.use(utilsAPIRouter.routes(), utilsAPIRouter.allowedMethods());
app.use(errorViewRouter.routes(), errorViewRouter.allowedMethods());// 放在最后面

// error-handling
app.on("error", (err, ctx) => {
  console.error("server error", err, ctx);   // 后台打印
});

module.exports = app;
